package com.yuji.aacar.net.core;

import com.yuji.aacar.net.convertfactory.JsonConverterFactory;
import com.yuji.aacar.net.entity.BaseEntity;
import com.yuji.aacar.net.exception.RetryWhenNetworkException;
import com.yuji.aacar.net.interceptor.MobileInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * <li>Package:com.ttp.http_core </li>
 * <li>Author: yhj </li>
 * <li>Date: 2017/2/15 </li>
 * <li>Description: 1001拿请求地址 </li>
 */
public class VersionHttpManager<Service> {
    protected static final int DEFAULT_TIMEOUT = 6;
    private Service httpService;
    private volatile static VersionHttpManager INSTANCE;
    //protected String url = "http://mobile.ttpai.cn/";
   // protected String url = "http://10.10.3.122/mobile/";
    //protected String url ="http://10.10.3.122/dealer/";
   // protected String url ="http://10.10.3.122/boss/";
   // protected String url ="http://10.10.3.122/customer/";
    protected String url ="http://10.10.3.122/checker/";
    private BaseEntity entity;

    //构造方法私有
    protected VersionHttpManager(Class<Service> aClass) {
        //手动创建一个OkHttpClient并设置超时时间
        httpService = createService(url, aClass);

    }

    public Service createService(String url, Class<Service> aClass) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        builder.addInterceptor(new MobileInterceptor());
        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(JsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(url)
                .build();
        return retrofit.create(aClass);
    }


    //获取单例
    public static VersionHttpManager getInstance(Class aClass) {
        if (INSTANCE == null) {
            synchronized (HttpManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new VersionHttpManager(aClass);
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 处理http请求
     *
     * @param observable
     */


    public void doHttpDeal(Observable observable) {
        observable
                .retryWhen(new RetryWhenNetworkException())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(entity.getSubscirber());
    }

    public static Object getHttpService(Class aClass,BaseEntity baseEntity) {
        getInstance(aClass).entity=baseEntity;
        return getInstance(aClass).httpService;
    }
}
